package com.zmn.mcc.admin.controller.common.download;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.*;

/**
 * 通用文件下载
 *
 * @author linfeng
 * @version v1.0
 * @since 2020/06/07 14:18
 */
@Controller
@RequestMapping("/common/")
public class FileDownLoadController {

    private Logger logger = LoggerFactory.getLogger(FileDownLoadController.class);

    @RequestMapping(value = "download")
    public void downloadFile(HttpServletRequest request,HttpServletResponse response, String urlFile) {
        String urlPath = urlFile;
        BufferedInputStream bin = null;
        HttpURLConnection httpURLConnection = null;
        OutputStream out = null;
        String[] params = urlPath.split("/");
        String fileName = "default.file";
        if (params != null && params.length > 0) {
            fileName = params[params.length - 1];
        }
        // 设置强制下载不打开
        response.setContentType("application/force-download");
        try {
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("不支持的编码格式", e);
        }
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000*5);
            //设置请求方式，默认是GET
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();

            // 建立链接从请求中获取数据
            bin = new BufferedInputStream(httpURLConnection.getInputStream());

            out = response.getOutputStream();
            int size = 0;
            long len = 0;
            byte[] buf = new byte[2048];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
            }
            // 关闭资源
            bin.close();
            out.close();
            logger.info("文件下载成功,文件大小："+len/1024+"kb");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("文件下载失败！", e);
        } finally {
            if (bin != null) {
                try {
                    bin.close();
                } catch (IOException e) {
                    logger.error("BufferedInputStream流关闭失败！", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("OutputStream流关闭失败！", e);
                }
            }
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
    }
}

